from django.shortcuts import render,get_object_or_404,redirect
from .models import Post
from .form import PostForm
def post_list(request):
    posts=Post.objects.all().order_by('publish_date')
    return render(request,'post_list.html',{'posts':posts})
def post_detail(request,pk):
    post=get_object_or_404(Post, pk=pk)
    return render(request,'post_detail.html',{'post':post})
def post_create(request):
    # if request.method=="POST":
    #     form = PostForm(request.POST)
    #     if form.is_valid():
    #         post = form.save(commit=False)
    #         post.author=request.user
    #         post.save()
    #         return redirect('post_detail',et=post.et)
    # else:
    #     form=PostForm()
    # return render(request,'post_edit.html',{'form':form})
    if request.method == "POST":
        form = PostForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('post_detail',pk=form.instance.pk)
    else:
        form = PostForm()
    return render(request, 'post_edit.html', {'form': form})

def post_update(request,pk):
    post=get_object_or_404(Post,pk=pk)
    if request.method=='POST':
        form=PostForm(request.POST,instance=post)
        if form.is_valid():
            form.save()
            return redirect('post_detail',pk=post.pk)
    else:
        form=PostForm(instance=post)
    return render(request,'post_edit.html',{'form':form})


def post_delete(request,pk):
    post=get_object_or_404(Post,pk=pk)
    post.delete()
    return redirect('post_list')
# Create your views here.
